package com.acce.base.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;

public class TokenUtils {
	
	public static String getToken() throws NoSuchAlgorithmException{
		String token = null;
		MessageDigest digest = MessageDigest.getInstance("SHA-1");
		String uuid = UUID.randomUUID().toString();
		String time = String.valueOf(System.currentTimeMillis());
		digest.update((uuid + time).getBytes());
		token = byte2hex(digest.digest());
		return token;
	}
	
	public static boolean compareSign(String sign, String token, String timestamp, String nonce) throws NoSuchAlgorithmException{
		boolean flag = false;
		String signServ = getSign(token, timestamp, nonce);
		if(sign.trim().equals(signServ.trim())){
			flag = true;
		}
		return flag;
	} 
	
	public static String getSign(String token, String timestamp, String nonce) throws NoSuchAlgorithmException{
		String sign = null;
		String[] arr = {token, timestamp, nonce};
		Arrays.sort(arr);
		StringBuffer buff = new StringBuffer();
		for(int i = 0; i < arr.length; i++){
			buff.append(arr[i]);
		}
		MessageDigest digest = MessageDigest.getInstance("SHA-1");
		digest.update(buff.toString().getBytes());
		sign = byte2hex(digest.digest());
		return sign;
	}
	
	 /** 
     * ���ֽ�����ת����16�����ַ��� 
     * @param b 
     * @return 
     */  
    private static String byte2hex(byte[] b) {  
        StringBuilder sbDes = new StringBuilder();  
        String tmp = null;  
        for (int i = 0; i < b.length; i++) {  
            tmp = (Integer.toHexString(b[i] & 0xFF));  
            if (tmp.length() == 1) {  
                sbDes.append("0");  	
            }  
            sbDes.append(tmp);  
        }  
        return sbDes.toString();  
    }  

	public static void main(String[] args) throws NoSuchAlgorithmException{
//		MessageDigest dig = MessageDigest.getInstance("SHA-1");
//		UUID uuid = UUID.randomUUID();
//		System.out.println(uuid);
//		dig.update(uuid.toString().getBytes());
//		System.out.println(dig.digest());
//		String a = byte2hex(dig.digest());
//		System.out.println(a);
		System.out.println(getToken());
//		System.out.println(getSign("411e7bc272a421b44802a9f608a740e5ca74872a", "20160606060606","123456789"));
		
		System.out.println(getSign("411e7bc272a421b44802a9f608a740e5ca74872a", "20160721100157","123456789"));
		System.out.println(Runtime.getRuntime().freeMemory() + ":" + 5L *1024L * 1024L );
	}
	
	 
}
